<?php
class News extends Admin_Controller{
	public $section 			 = 'article';
	private $path_article 		 = "uploads/news/";
	private $path_article_thumbs = "uploads/news/thumbs/";
	private $path_upload 		 = "";
//	private $path_thumbs = "";
//	private $path_home = "";
	private $folder;
	private $setting;
	private $page_size = 10;
	
	function __construct(){
		parent::__construct();	
		$this->load->model('news_model',"article_m");
		$this->load->model('news_category_model',"categories_m");
		$this->load->helper("MY_array");
	}
	public function index($page_index = 0 ){		
		$cat_select = "";
		$base_where = array();
		$base_where = $page_index? $base_where + array('limit' => $page_index) : $base_where;

		$model = $this->article_m->get_many_by($base_where,$this->page_size);//tra ve articles + total_row	
			
		$this->config->load("paging");
		$paging = $this->config->item("paging_admin");
		$paging["per_page"]		= $this->page_size;
		$paging["uri_segment"]  = 4;
		$paging["base_url"]     = site_url($this->config->item('admin_folder')."/news/index/");
		$paging["total_rows"] = $model->total_row;
		$this->pagination->initialize($paging);
		$paging = $this->pagination->create_links();

		$cat = $this->categories_m->get_all();
		$level1 = array();
		array_level1($cat,$level1);
		$cat_select = array_for_select($level1,'id','title','frefix');
		
		$data["model"] 		= $model->articles;
		$data["cat_select"] = $cat_select;
		$data["paging"]		= $paging;
		$data["page_index"] = $page_index;
		$this->view(config_item('admin_folder').'/news', $data);
		
	}	
	public function edit($id=0,$method=0){
		$this->load->helper("tags");
		if ($id > 0){
			$model = (array)$this->article_m->get($id);
			if ($model['date_start'] != 0) $model['date_start'] = date("d-m-Y H:i",$model['date_start']);
			if ($model['date_end'] != 0) $model['date_end'] = date("d-m-Y H:i",$model['date_end']);
		} else{
			$model['id'] = $id;
		}
		//print_r($this->input->post()) ;exit;
		if($this->input->post('slug') != @$model['slug']) {
			$is_unique =  '|is_unique[news_article.slug]';
			$this->form_validation->set_rules('slug',"liên kết tĩnh", 'required|trim|alpha_dash'.$is_unique);
        }
		$this->form_validation->set_rules('title',"tiêu đề",'required|max_length[80]');
		$this->form_validation->set_rules('cat_id',"danh mục tin",'required|max_length[80]');
		if ($this->form_validation->run() == TRUE){	
			$model = $this->input->post();		
			//UPLOAD IMAGE - News chi up va resize ko can save hinh f			
			//$model["bodyhtml"] = htmlentities($model["bodyhtml"], ENT_QUOTES, "UTF-8");
			if ($id > 0){
				$info_image = $this->image_upload("file",$id);
				$info_image2 = $this->image_upload("file2",$id,1);
				
				if(!empty($info_image["file_name"]))
					$model["image"] = $info_image["file_name"];
				if(!empty($info_image2["file_name"]))
					$model["image2"] = $info_image2["file_name"];
				$model["tags"] 		 = insert_tags($model["tags"]);
				$this->article_m->update($id,$model);
				$this->session->set_flashdata('message',"Cập nhật thành công");
				redirect(config_item('admin_folder').'/news/edit/'.$id);
			}
			else{
				$info_image = $this->image_upload();
				$info_image2 = $this->image_upload("file2");
				if(!empty($info_image["file_name"])){
					$model["image"] = $info_image["file_name"];
				}
				if(!empty($info_image2["file_name"])){
					$model["image2"] = $info_image2["file_name"];
				}
				$model["tags"] 		 = insert_tags($model["tags"]);
				$id_insert = $this->article_m->insert($model);
				$this->session->set_flashdata('message',"Thêm mới thành công");
				redirect(config_item('admin_folder').'/news');
			}
		}
		$category	= $this->db->get("news_categories")->result();
		if(!empty($category)) foreach($category as $item){
			$data["category"][$item->id] = $item->title;	
		}
		$data["tag_name"] = get_tags_name($model["tags"]);
		$data["model"] = $model;
		$this->view(config_item('admin_folder').'/news_form',$data);
	}
	public function delete($id,$page_index){
		$this->delete_img($id,0);
		$this->delete_img($id,0,1);
		$this->article_m->delete($id);
		if(!empty($page_index))
			redirect("admin/news/index/".$page_index);
		else
			redirect("admin/news");
	}
	function image_upload($name_input_upload="file",$id_image_delete=0)
	{
		$data['file_name'] = false;
		$data['error']	= false;
		$config['allowed_types'] = 'gif|jpg|png';
		//$config['max_size']	= $this->config->item('size_limit');
		$config['upload_path'] = 'uploads/images/full/news/';
		if(!is_dir($config["upload_path"])){
			mkdir($config["upload_path"],0777);
			chmod($config["upload_path"],0777);
		}
		if(!is_dir('uploads/images/medium/'."/news")){
			mkdir('uploads/images/medium/'."/news",0777);
			chmod('uploads/images/medium/'."/news",0777);
		}
		if(!is_dir('uploads/images/small/'."/news")){
			mkdir('uploads/images/small/'."/news",0777);
			chmod('uploads/images/small/'."/news",0777);
		}
		if(!is_dir('uploads/images/thumbnails/'."/news")){
			mkdir('uploads/images/thumbnails/'."/news",0777);
			chmod('uploads/images/thumbnails/'."/news",0777);
		}
		$config['encrypt_name'] = true;
		$config['remove_spaces'] = true;
		
		$this->load->library('upload', $config);
		if ( $this->upload->do_upload($name_input_upload))
		{
			if(!empty($id_image_delete))
				$this->delete_img($id_image_delete,0);
			$upload_data	= $this->upload->data();
			$this->load->library('image_lib');
			//this is the larger image

			$config['image_library'] = 'gd2';
			$config['source_image'] = 'uploads/images/full/news/'.$upload_data['file_name'];
			$config['new_image']	= 'uploads/images/medium/news/'.$upload_data['file_name'];
			$config['maintain_ratio'] = TRUE;
			$config['width'] = 600;
			$config['height'] = 500;
			$this->image_lib->initialize($config);
			$this->image_lib->resize();
			$this->image_lib->clear();

			//small image
			$config['image_library'] = 'gd2';
			$config['source_image'] = 'uploads/images/medium/news/'.$upload_data['file_name'];
			$config['new_image']	= 'uploads/images/small/news/'.$upload_data['file_name'];
			$config['maintain_ratio'] = TRUE;
			$config['width'] = 235;
			$config['height'] = 235;
			$this->image_lib->initialize($config); 
			$this->image_lib->resize();
			$this->image_lib->clear();

			//cropped thumbnail
			$config['image_library'] = 'gd2';
			$config['source_image'] = 'uploads/images/small/news/'.$upload_data['file_name'];
			$config['new_image']	= 'uploads/images/thumbnails/news/'.$upload_data['file_name'];
			$config['maintain_ratio'] = TRUE;
			$config['width'] = 150;
			$config['height'] = 150;
			$this->image_lib->initialize($config); 	
			$this->image_lib->resize();	
			$this->image_lib->clear();

			$data['file_name']	= $upload_data['file_name'];
		}
		
		if($this->upload->display_errors() != '')
		{
			$data['error'] = $this->upload->display_errors();
		}
		return $data;
	}
	function delete_img($id,$active_update = 1,$index_input=0){
		$info_img = $this->db->select("id,image,image2")->where("news_article.id",$id)->get("news_article")->row();
		if(!empty($info_img)){
			$name_image = (empty($index_input))?$info_img->image:$info_img->image2;
			$colum_image = (empty($index_input))?"image":"image2";
			@unlink("uploads/images/full/news/".$name_image);
			@unlink("uploads/images/medium/news/".$name_image);
			@unlink("uploads/images/small/news/".$name_image);	
			@unlink("uploads/images/thumbnails/news/".$name_image);	
			if($active_update ==1)
				$this->db->where("id",$id)->update("news_article",array($colum_image=>""));
		}
		if($active_update == 1)
			redirect("admin/news/edit/".$id);
	}
	function bulk_save($page=0){
		$post	= $this->input->post();
		$list_update = "";
		$this->load->helper("handle_string");
		foreach($post["title"] as $id => $value){
			$list_update[] = array("title"=>$value,
								   "slug"=>utf8_to_ascii($value),
								   "cat_id"=>$post["cat_id"][$id],
								   "active"=>$post["active"][$id],
								   "id"=>$id,
							);
		}
		if(!empty($list_update)){
			$this->db->update_batch("news_article",$list_update,"id");	
		}
		$this->session->set_flashdata('message',"Cập nhật thành công");
		if($page != 0)
			redirect("admin/news/index/".$page);
		else
			redirect("admin/news");
	}
	function copy_data($id,$page_index){
		$info_data = $this->db->select("image,title,slug,cat_id,keywords,description,bodyhtml,active")->where("news_article.id",$id)->get("news_article")->row();
		if(!empty($info_data)){
			$rand = rand(1,100);
			$info_data->slug  = $info_data->slug."_".$rand;
			$info_data->title  = $info_data->title."(".$rand.")";
			$info_data->created = time();
			$this->db->insert("news_article",$info_data);
			$id_insert = $this->db->insert_id();
			redirect("admin/news/edit/".$id_insert);
		}
		$this->session->set_flashdata('message',"Xảy ra lỗi trong quá trình copy");
		redirect("admin/news");
	}
}